<script setup lang="ts">
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { GetIndividualVolunteerActivities } from '@/api/volunteer'
import { getUserMessageList } from '@/api/user'
import { getActivityChief } from '@/api/activity'
import { GetIndividualVolunteerActivitiesResponse } from '@/types/volunteer'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { userMessage } from '@/types'
import { ElMessage } from 'element-plus'
import * as signalR from '@microsoft/signalr'
import dayjs from 'dayjs'

//展示志愿数据
let tableData = ref<Array<GetIndividualVolunteerActivitiesResponse>>()
const myActivities = await GetIndividualVolunteerActivities()
tableData = ref(myActivities.data)

let router = useRouter()
//点击活动跳转
const lookActivityDetail = (row: GetIndividualVolunteerActivitiesResponse) => {
  console.log(row)
  router.push({ path: '/VolunteerHome', query: { myEnlistActivityId: row.activityId } })
}
//刷新志愿活动
const Refresh = async () => {
  tableData.value = (await GetIndividualVolunteerActivities()).data
}

//给表格每一列设置颜色
const tableRowClassName = ({ row }: { row: GetIndividualVolunteerActivitiesResponse }): string => {
  if (row.activityCompleted) {
    return 'warning-row'
  } else if (dayjs(row.activityStartTime) > dayjs()) {
    return 'success-row'
  } else if (dayjs(row.activityStartTime) < dayjs() && dayjs(row.activityEndTime) > dayjs()) {
    return 'primary-row'
  } else {
    return 'danger-row'
  }
}

//用户数据
const userStore = useUserStore()

//启动连接
const server = new signalR.HubConnectionBuilder()
  .withUrl('http://localhost:900/VoluntaryIdentity/Signalr/Hubs/ChatRoomHub', {
    // 设置是否跳过提升
    skipNegotiation: true,
    // 设置传输类型
    transport: signalR.HttpTransportType.WebSockets,
    accessTokenFactory: () => userStore.token
  }) // 设置日志级别
  .configureLogging(signalR.LogLevel.Information)
  // 构建HubConnection
  .build()

onMounted(async () => {
  //启动连接
  await server.start()

  //接受消息
  server.on('sendActivityMessage', async (msg: userMessage) => {
    userStore.setUserMessage(msg)
    let res = (await getActivityChief(msg.activityId)).data
    ElMessage.success(res.activityName + '有新的通知')
    console.log(msg)
  })
})

//查看用户通知
const activityMessage = ref(false)
const openActivityMessageId = ref<number>()
const messageData = ref<Array<userMessage>>([])
const openActivityMessage = (row: GetIndividualVolunteerActivitiesResponse) => {
  openActivityMessageId.value = row.activityId
  messageData.value = userStore.userMessage.filter((item) => item.activityId == row.activityId)
  activityMessage.value = true
}

//刷新消息
const refreshMessage = async (activityId: number) => {
  var result = (await getUserMessageList(activityId)).data
  result.forEach((element) => {
    if (userStore.userMessage.filter((item) => item.messageId === element.messageId).length === 0) {
      userStore.setUserMessage(element)
    }
  })
  messageData.value = userStore.userMessage.filter((item) => item.activityId == activityId)
}

//获取活动状态函数
const getActivityStatus = (row: GetIndividualVolunteerActivitiesResponse): string => {
  if (dayjs(row.activityStartTime) > dayjs()) {
    return '准备中'
  } else if (dayjs(row.activityStartTime) <= dayjs() && dayjs(row.activityEndTime) >= dayjs()) {
    return '进行中'
  } else {
    return '已结束'
  }
}

// 摧毁组件时断开连接
onBeforeUnmount(() => {
  server.stop()
})
</script>

<template>
  <el-container>
    <el-header>
      <el-row style="background-color: #ffffff">
        <el-col :span="6">
          <el-statistic title="参加的全部志愿活动" :value="myActivities.data.length"></el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="正在准备的志愿活动"
            :value="myActivities.data.filter((item) => !item.activityCompleted && dayjs(item.activityStartTime) > dayjs()).length"
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="正在进行的志愿活动"
            :value="
              myActivities.data.filter((item) => !item.activityCompleted && dayjs(item.activityStartTime) < dayjs() && dayjs(item.activityEndTime) > dayjs())
                .length
            "
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="已结束的志愿活动"
            :value="myActivities.data.filter((item) => item.activityCompleted || dayjs(item.activityEndTime) < dayjs()).length"
          >
            <template #suffix>/{{ myActivities.data.length }}</template>
          </el-statistic>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" style="width: 100%; height: 100%" v-if="tableData?.length !== 0" :row-class-name="tableRowClassName">
        <el-table-column label="参加日期">
          <template #default="scope">
            {{ dayjs(scope.row.activityEnlistTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="activityName" label="名称" />
        <el-table-column prop="activityType" label="活动类型" />
        <el-table-column label="活动状态">
          <template #default="scope">
            {{ getActivityStatus(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="activityAddress" label="活动地址" />
        <el-table-column fixed="right" label="操作">
          <template #default="scoped">
            <el-button link type="primary" size="small" @click="lookActivityDetail(scoped.row)">查看详情</el-button>
            <el-button link type="primary" size="small" @click="openActivityMessage(scoped.row)"
              >查看通知({{ userStore.userMessage.filter((item) => item.activityId === scoped.row.activityId).length }})
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="你还没有参加任何活动">
        <el-button type="primary" @click="Refresh">刷新</el-button>
      </el-empty>
      <el-dialog v-model="activityMessage" title="活动通知">
        <template #header>
          <el-button type="primary" @click="refreshMessage(openActivityMessageId!)" round> 刷新消息 </el-button>
        </template>
        <el-table :data="messageData" stripe v-if="messageData.length !== 0">
          <el-table-column prop="createTime" label="发送时间">
            <template #default="scope">
              {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="message" label="通知" />
        </el-table>
        <el-empty v-else description="暂无通知"></el-empty>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<style scoped>
.el-col {
  text-align: center;
}

.el-table >>> .warning-row {
  background: rgb(244, 234, 215);
}

.el-table >>> .success-row {
  background: rgb(214, 243, 203);
}

.el-table >>> .primary-row {
  background: rgb(209, 241, 247);
}

.el-table >>> .danger-row {
  background-color: rgb(245, 223, 214);
}
</style>
